package com.kaixinff.kaixin001.servlet;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.kaixinff.kaixin001.util.Filter;
import com.kaixinff.kaixin001.util.KXClient;
import com.kaixinff.kaixin001.util.KXUtil;
import com.kaixinff.kaixin001.util.RegStep;
import com.kaixinff.name.User;

@SuppressWarnings("serial")
public class XWInviteServlet extends HttpServlet {
	private static final String INDEX_URL = KXUtil.HOST_URL + "/!spiderman/index.php";

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		List<User> users = KXUtil.getUsers(new Filter(){
			@Override
			public boolean access(User user) {
				return user.hasStep(RegStep.ADD_XW);
			}}, resp);
		if (users == null) {
			return;
		}
		
		for (User user: users) {
			KXClient client = KXClient.getInstance(user.getId());
			String html = client.doGet(INDEX_URL, null).getContent();
			String cid = getCid(html);
			Pattern p = Pattern.compile("有(\\d+?)个邀请函未处理");
			Matcher m = p.matcher(html);
			if (m.find()) {
				String url = KXUtil.HOST_URL + "/!spiderman/invite.php";
				client.doGet(url, INDEX_URL);
				String agreeUrl = KXUtil.HOST_URL + "/!spiderman/!ajax_invite.php?flag=agreeall&cid=" + cid + "&tmp=" + Math.random() + "&rt=json";
				client.doGet(agreeUrl, url);
				System.out.println("");
				html = client.doGet(INDEX_URL, url).getContent();
			}
			p = Pattern.compile("<a href=\"/!spiderman/team.php\">我的团队</a>[(]<b id=\"user_teamnum\">(\\d+?)</b>[)]");
			m = p.matcher(html);
			if (m.find()) {
				int teamnum = Integer.parseInt(m.group(1));
				if (teamnum < 16) {
					p = Pattern.compile("javascript[:]XW[.]Install[.]invite[(]\\[(\\d+?)\\],'team'[)];");
					m = p.matcher(html);
					int i = 16 - teamnum;
					while (m.find()) {
						String uid = m.group(1);
						String inviteUrl = KXUtil.HOST_URL + "/!spiderman/!ajax_invite.php?flag=team&uids=" + uid + "&cid=" + cid + "&tmp=" + Math.random() + "&rt=json";
						client.doGet(inviteUrl, INDEX_URL);
						i--;
						if (i == 0) {
							break;
						}
					}
				}
			}
		}
	}
	
	private String getCid(String html) {
		Pattern p = Pattern.compile("\"cid\"[:]\"(\\d+?)\"");
		Matcher m = p.matcher(html);
		if (m.find()) {
			return m.group(1);
		}
		return "2";		
	}
}
